package com.atguigu.edu.controller;


import com.atguigu.commonUtils.R;
import com.atguigu.edu.entity.Video;
import com.atguigu.edu.feign.VodClient;
import com.atguigu.edu.service.VideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author Rayyy666
 * @since 2022-04-02
 */
@RestController
@RequestMapping("/edu/video")
//@CrossOrigin //解决跨域问题
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private VodClient vodClient;

    /**
     * 添加小节
     *
     * @param video
     * @return
     */
    @PostMapping("addVideo")
    public R addVideo(@RequestBody Video video) {
        videoService.save(video);

        return R.ok();
    }

    /**
     * 删除小节，删除对应的阿里云视频
     *
     * @param videoId
     * @return
     */
    @DeleteMapping("deleteVideo/{videoId}")
    public R deleteVideo(@PathVariable String videoId) {
        //先根据小节ID获取到视频ID，再调用方法实现视频删除
        Video video = videoService.getById(videoId);

        //先删除 视频 再删除小节信息，先删除小节，视频就会查不到
        String videoSourceId = video.getVideoSourceId();
        //判断小节里是否有 阿里云视频ID
        if (!StringUtils.isEmpty(videoSourceId)) {
            //根据视频ID 远程调用实现删除
            R result = vodClient.removeALiYunVideoById(videoSourceId);
            if (result.getCode() == 20001) {
                throw new GuliException(20001, "删除视频失败，熔断器方法执行.......");
            }
        }
        videoService.removeById(videoId);
        return R.ok();
    }

    /**
     * 修改小节
     *
     * @param video
     * @return
     */
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody Video video) {
        videoService.updateById(video);
        return R.ok();
    }

    /**
     * 根据小节ID查询 小节信息
     *
     * @param videoId
     * @return
     */
    @GetMapping("getVideoInfo/{videoId}")
    public R getVideoInfo(@PathVariable String videoId) {
        Video video = videoService.getById(videoId);
        return R.ok().data("video", video);
    }
}

